#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangWlmqQuPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_wlmq_qu_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "乌鲁木齐市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    def start_requests(self):
        for source, county, url in [
            ['乌鲁木齐市米东区人民政府', "米东区", "http://www.xjmd.gov.cn/info/iList.jsp?isSd=false&node_id=GKrmzf&cat_id=10974&tm_id=67&cur_page=1"],
            ['乌鲁木齐市米东区人民政府', "米东区", "http://www.xjmd.gov.cn/info/nIndex.jsp?node_id=GKrmzf&cat_id=10869"],
            ['乌鲁木齐市水磨沟区人民政府', "水磨沟区", "http://www.xjsmgq.gov.cn/info/iList.jsp?cat_id=13985&tm_id=120&cur_page=1"],
            ['乌鲁木齐市水磨沟区人民政府', "水磨沟区", "http://www.xjsmgq.gov.cn/info/iList.jsp?isSd=false&node_id=GKbgs&cat_id=12385"],
            ['乌鲁木齐市水磨沟区人民政府', "水磨沟区", "http ://www.xjsmgq.gov.cn/info/iList.jsp?isSd=false&node_id=GKbgs&cat_id=12386"],
            ['乌鲁木齐市水磨沟区人民政府', "水磨沟区", "http://www.xjsmgq.gov.cn/info/iList.jsp?isSd=false&node_id=GKbgs&cat_id=13369"],
            ['乌鲁木齐市达坂城区', "达坂城区", "http://www.dabancheng.gov.cn/info/iList.jsp?cat_id=15957"],
            ['乌鲁木齐市达坂城区', "达坂城区", "http://www.dabancheng.gov.cn/info/iList.jsp?cat_id=16522"],
        ]:
            params = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query))
            if 'info/iList.jsp' in url:
                callback = self.parse_list
            else:
                callback = self.parse_content
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=callback, meta={'item': item, 'params': params})

    def parse_content(self, response, **kwargs):
        params = response.meta.get('params')
        params['cur_page'] = "1"
        yield response.follow("/info/iList.jsp" + '?' + urllib.parse.urlencode(params), callback=self.parse_list,
                              meta=response.meta)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath("//*[@class='am-tabs-bd' or @class='centers_left_list_tree']//tr//a[contains(@href, 'htm') or @title]/ancestor::tr[string-length(string(.))>=5] | "
                                   "//*[@class='yc_right_comlist']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5] | "
                                   "//div[@class='zfxxgk_right']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            # item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath(".").re_first(r"""共\s*(\d+)\s*页""") or response.xpath(".").re_first(r"""第\d+/(\d+)\s*页""")
            params = response.meta['params']
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                params['cur_page'] = str(page_num)
                yield response.follow("/info/iList.jsp" + '?' + urllib.parse.urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_wlmq_qu_policy".split())
